package com.hzqy.web.ac;

import com.hzqy.commons.service.AuthenticatedService;
import com.hzqy.service.commons.CommonsServiceBean;
import com.hzqy.service.hqjc.PayServiceBean;
import com.hzqy.web.login.SessionKey;
import com.hzqy.web.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/")
public class PayAction {
	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	@Resource
	private PayServiceBean payServiceBean;
	@Resource
	private CommonsServiceBean commonsServiceBean;

	//同步信息入库
	@RequestMapping("/service/VASBack")
	public Object vasBack(int type,String userId,String productId,String startTime,String endTime,String returnUrl,String contentName,HttpServletRequest request) {
		LOG.debug(userId+"服务开始回调(0定,1退)类型为type="+type);
		UserBillVo ubv = new UserBillVo();
		ubv.setF_ub_type(type);
		ubv.setF_ub_serverid(userId);
		ubv.setF_sp_productcode(productId);
		ubv.setF_ui_resolution(0);
		if(contentName == null || "null".equals(contentName) || "".equals(contentName)){
			contentName = "vasBack";
		}
		ubv.setF_ub_source(contentName);
		if(endTime!=null && endTime.trim().length()>0) {
			try {
				Date date = new SimpleDateFormat("yyyyMMddhhmmss").parse(endTime);
				endTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date);
				Date date2 = new SimpleDateFormat("yyyyMMddhhmmss").parse(startTime);
				startTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date2);

			} catch (ParseException e) {
				LOG.error("服务回调VASBACK的时间格式化出错",e);
			}
			ubv.setF_ub_ordertime(startTime);
			ubv.setF_ub_endtime(endTime);
		}
		int flag = payServiceBean.insertUserBill(ubv);
		String code = "";
		String message = "";
		if(flag == 1){
			code="0";
			message = "数据插入成功";
		}else{
			code="3";
			message = "数据插入失败";
		}
		try {
			message = URLEncoder.encode(URLEncoder.encode(message,"UTF-8"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			LOG.error("服务回调VASBACK的结果信息格式化出错：",e);
		}
		if(returnUrl == null || "null".equals(returnUrl) || "".equals(returnUrl)){
			returnUrl ="../service/serviceVASBack.jsp";
		}
		returnUrl = returnUrl+"?code="+code+"&message="+message;
		return "redirect:"+returnUrl;
	}

	//订购信息入库
	@RequestMapping("/service/orderBack")
	public Object orderBack(String Result,HttpServletRequest request) {
		LOG.debug("订购入库回调(0成功,其他失败)结果为result="+Result);

		HttpSession session=request.getSession();
		String userId = (String)session.getAttribute(SessionKey.SESSION_SERVERID);
		String returnUrl = (String)session.getAttribute(userId+"returnUrl");
		int result = 1;

		if(Result == "0" || "0".equals(Result)){
			int resolution = Integer.parseInt((String)session.getAttribute(SessionKey.SESSION_EPG_RESOLUTION));
			String productId = (String)session.getAttribute(userId+"productId");
			String subSource = (String)session.getAttribute(userId+"subSource"); //定购来源
			if(subSource == null || subSource.trim().length()==0)
				subSource = "default";
			String unsubFlag = (String)session.getAttribute("unsubFlag");
			if("3".equals(unsubFlag)){//退订不修改result值

			}else{
				result = Integer.parseInt(Result);
			}

			LOG.debug("订购入库数据为userId="+userId+"--resolution="+resolution+"--productId="+productId+"--subSource="+subSource);

			UserBillVo ubv = new UserBillVo();
			ubv.setF_ub_type(result);
			ubv.setF_ub_serverid(userId);
			ubv.setF_ui_resolution(resolution);
			ubv.setF_sp_productcode(productId);
			ubv.setF_ub_source(subSource);
			String endTime = "20991231235959";
			try {
				java.util.Date date = new SimpleDateFormat("yyyyMMddhhmmss").parse(endTime);
				endTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date);
			} catch (ParseException e) {
				LOG.error("服务回调VASBACK的时间格式化出错",e);
			}
			ubv.setF_ub_endtime(endTime);

			payServiceBean.insertOrderUserBill(ubv);
		}
		String SerStartTime = String.valueOf(request.getParameter("SerStartTime"));
		String SerEndTime = String.valueOf(request.getParameter("SerEndTime"));

		if(returnUrl.indexOf("?") != -1){
			returnUrl = returnUrl+"&Result="+result+"&SerStartTime="+SerStartTime+"&SerEndTime="+SerEndTime;
		}else{
			returnUrl = returnUrl+"?Result="+result+"&SerStartTime="+SerStartTime+"&SerEndTime="+SerEndTime;
		}

		return "redirect:"+returnUrl;
	}

	//周免信息同步入库
	@RequestMapping("/weekFree/insertCoupon")
	@ResponseBody
	public Object insertWeekFreeVo(String userid,String contentid,String starttime,String endtime,String drawtime,HttpServletRequest request){
		HttpSession session=request.getSession();
		String res = (String)session.getAttribute(SessionKey.SESSION_EPG_RESOLUTION);
		int resolution = 0;
		if(!("".equals(res)||"null".equals(res)||res==null)){
			resolution = Integer.parseInt(res);
		}

		Map<String,Object> map = new HashMap<String,Object>();
		UserBillVo ubv = new UserBillVo();
		ubv.setF_ub_type(0);
		ubv.setF_ub_serverid(userid);
		ubv.setF_sp_productcode(contentid);
		ubv.setF_ub_source("weekFree"+contentid);
		ubv.setF_ui_resolution(resolution);
		if(drawtime!=null && drawtime.trim().length()>0) {
			try {
				Date date = new SimpleDateFormat("yyyyMMddHHmmss").parse(drawtime);
				drawtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
				Date date2 = new SimpleDateFormat("yyyyMMddHHmmss").parse(endtime);
				endtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date2);
				Date date3 = new SimpleDateFormat("yyyyMMddHHmmss").parse(starttime);
				starttime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date3);

			} catch (ParseException e) {
				LOG.error("营销栏目回调insertCoupon的时间格式化出错",e);
			}
		}
		ubv.setF_ub_ordertime(drawtime);//领取时间
		ubv.setF_ub_endtime(endtime);//有效结束时间
		ubv.setF_ub_unsubtime(starttime);//有效开始时间

		int flag = payServiceBean.insertUserBillForWeekFree(ubv);
		int result = 0;
		String message = "";
		if(flag == 1){
			result = 0;
			message = "数据插入成功！";
		}else{
			result = 3;
			message = "数据插入失败！";
		}
		try {
			message = URLEncoder.encode(URLEncoder.encode(message,"UTF-8"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			LOG.error("营销栏目回调insertCoupon的结果信息格式化出错：",e);
		}
		//returnUrl = returnUrl+"?result="+result+"&message="+message;
		map.put("result",result);
		map.put("message",message);
		return map;
	}

	//产品鉴权
	@RequestMapping("/service/authenticationByProductID")
	@ResponseBody
	public Object getAuthenticatedResultByProductID(AuthenticatedVo authVo,HttpServletRequest request,HttpServletResponse response) {
		AuthenticatedService authenticatedService = new AuthenticatedService(request,response);
		authVo.setReadTimeOut(3000);
		authVo.setConnectTimeout(3000);
		String Result= authenticatedService.getAuthenticatedResultByProductID(authVo);
		Map<String, String> map=new HashMap<String, String>();
		map.put("Result", Result);
		return map;
	}
	//产品列表鉴权
	@RequestMapping("/service/authenticationByProductIDS")
	@ResponseBody
	public Object getAuthenticatedResultByProductIDS(AuthenticatedVo authVo,HttpServletRequest request,HttpServletResponse response) {
		AuthenticatedService authenticatedService = new AuthenticatedService(request,response);
		List<Map> list=new ArrayList<Map>();

		String[] strlist=authVo.getProductCodes().split(",");
		for(int i = 0; i < strlist.length; i++) {
			if(strlist[i].length()>=4) {
				Map<String, String> map=new HashMap<String, String>();
				try {
					map.put("productId",strlist[i]);
					map.put("result", "504");
					list.add(map);
				} catch(Exception e) {
					LOG.error("广场舞产品鉴权转换错误。");
				}
			}
		}
		String Result="504";
		//int count=0;
		for (Map map : list) {
			String productId=String.valueOf(map.get("productId"));
			authVo.setProductCode(productId);
			authVo.setReadTimeOut(3000);
			authVo.setConnectTimeout(3000);
			Result=authenticatedService.getAuthenticatedResultByProductID(authVo);
			map.put("result",Result);
			//count=count+1;
		}
		//map.put("count",count+"");//用户已订购几次产品
		return list;
	}

	//服务鉴权
	@RequestMapping("/service/authenticationByServiceID")
	@ResponseBody
	public Object getAuthenticatedResult(String userID,String serviceID,HttpServletRequest request,HttpServletResponse response) {
		AuthenticatedService authenticatedService = new AuthenticatedService(request,response);
		Integer readTimeOut = 3000;
		Integer connectTimeout = 3000;
		String Result= authenticatedService.getAuthenticatedResult(userID,serviceID,readTimeOut,connectTimeout);
		Map<String, String> map=new HashMap<String, String>();
		map.put("Result", Result);
		return map;
	}

	/**
	 * 产品包鉴权
	 * @param userID				用户账号
	 * @param productMultirateID	产品包id
	 * @param request
	 * @param response
	 * @return map{
	 * 				Result:鉴权结果
	 * 				desc:描述
	 * 				productCode:产品code 对应表sys_product——f_sp_productcode字段
	 * 				productType:产品类型 对应表sys_product——f_sp_type字段
	 * 				productId:产品id 对应表sys_product——f_sp_id字段
	 * 				SPID:企业spid 对应表pms_org——f_po_code字段
	 * 				}
	 */
	@RequestMapping("/service/authenticationByProductMultirateID")
	@ResponseBody
	public Object getAuthenticatedResultByProductMultirateID(AuthenticatedVo authVo,HttpServletRequest request,HttpServletResponse response) {
		String Result = "504";
		Map<String, String> map=new HashMap<String, String>();
		List<SysProductVo> productList = commonsServiceBean.selectProductListByProductId(authVo.getProductMultirateID());
		if(productList==null||productList.size()==0) {//不存在数据
			map.put("Result", "-1");
			map.put("desc", "查询无此产品包，异常！");
		}else{
			Integer readTimeOut = 1000;
			Integer connectTimeout = 1000;
			AuthenticatedService authenticatedService = new AuthenticatedService(request,response);
			SysProductVo productVo = null;
			//**************
			boolean batchauth = false;//是否调用批量鉴权
			for(int i = 0; i < productList.size(); i++) {
				productVo = productList.get(i);
				if(productVo.getF_sp_type()==11) {// 当后台配置了产品类型为11(批量包) 就调用批量鉴权的接口
					batchauth = true;
					break;
				}
			}
			if(batchauth) {//调用批量鉴权接口
				AuthenticatedVo tmpauthVo = new AuthenticatedVo();
				tmpauthVo.setServerid(authVo.getServerid());
				if(productVo!=null)
					tmpauthVo.setProductCode(productVo.getF_sp_productcode());
				tmpauthVo.setReadTimeOut(readTimeOut);
				tmpauthVo.setConnectTimeout(connectTimeout);
				Map<Object, Object> resMap = authenticatedService.getAuthenticatedResultByBatchInterface(tmpauthVo,productList);
				Result = (String) resMap.get("result");
				String batchauthresult = (String) resMap.get("batchauthresult");
				map.put("batchauthresult", batchauthresult);
			}else {//**************
				for(int i = 0; i < productList.size(); i++) {
					productVo = productList.get(i);
					if(productVo.getF_sp_type()==10) { //10代表为服务ID
						Result= authenticatedService.getAuthenticatedResult(authVo.getServerid(),productVo.getF_sp_productcode(),readTimeOut,connectTimeout);
						//break; //如果为服务ID，则只需要鉴权一次就要break，前期因教育K歌业务很多产品包没有服务id，所以要循环统一
					} else { //其他为产品ID
						authVo.setProductCode(productVo.getF_sp_productcode());
						Result= authenticatedService.getAuthenticatedResultByProductID(authVo);
					}
					if(Result=="0"||"0".equals(Result)) {
						break;
					}
				}
			}
			int flag = 0; //判断是否取到包月产品ID，如果未取到需要取第1个产品id，0为服务id
			for(int i = 0; i < productList.size(); i++) { //为了获取可被定购的产品id，默认给包月产品id，当没有包月产品id时，应提取第一个产品id，程序不判断是单点还是其他包季包年等。
				productVo = productList.get(i);
				if(productVo.getF_sp_type()==1) { //1代表包月
					map.put("productCode", productVo.getF_sp_productcode());
					map.put("productType", productVo.getF_sp_type()+"");
					map.put("productId", productVo.getF_sp_id()+"");
					flag = 1;
					break;
				}
			}
			if(flag==0 && productList.size()>=2) { //判断是否取到包月产品ID，如果未取到需要取第1个产品id，0为服务id
				productVo = productList.get(1);
				map.put("productCode", productVo.getF_sp_productcode());
				map.put("productType", productVo.getF_sp_type()+"");
				map.put("productId", productVo.getF_sp_id()+"");
			}
			if(map.get("productId")!=null){
				List<PmsOrgVo> orgList=commonsServiceBean.selectOrgCodeByProductId(Integer.parseInt(map.get("productId")));
				String SPID="";
				if(orgList!=null && orgList.size() > 0){
					SPID=orgList.get(0).getF_po_code();
				}
				if(SPID ==""||"".equals(SPID)){
					SPID="120000";
				}
				map.put("SPID", SPID);
			}
			map.put("Result", Result);
		}
		return map;
	}
	/**
	 * 根据分类id鉴权
	 * @param userID		用户账号
	 * @param categoryId	分类id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/service/authenticationByCategoryID")
	@ResponseBody
	public Object getAuthenticatedResultByCategoryID(String userID,int categoryId,HttpServletRequest request,HttpServletResponse response){
		String Result = "504";
		String wfResult = "504";
		Map<String, String> map=new HashMap<String, String>();
		List<SysProductVo> productList=commonsServiceBean.selectProductListByCatalogId(categoryId);
		if(productList==null||productList.size()==0) {//不存在数据
			map.put("Result", "-1");
			map.put("desc", "查询无此产品包，异常！");
		}else{
			Integer readTimeOut = 1000;
			Integer connectTimeout = 1000;
			AuthenticatedService authenticatedService = new AuthenticatedService(request,response);
			SysProductVo productVo = null;
			boolean batchauth = false;//是否调用批量鉴权
			for(int i = 0; i < productList.size(); i++) {
				productVo = productList.get(i);
				//LOG.debug("鉴权产品类型:"+productVo.getF_sp_type());
				if(productVo.getF_sp_type()==11) {// 当后台配置了产品类型为11(批量包) 就调用批量鉴权的接口
					batchauth = true;
					break;
				}
			}
			if(batchauth) {//调用批量鉴权接口
				AuthenticatedVo authVo = new AuthenticatedVo();
				authVo.setServerid(userID);
				if(productVo!=null)
					authVo.setProductCode(productVo.getF_sp_productcode());
				authVo.setReadTimeOut(readTimeOut);
				authVo.setConnectTimeout(connectTimeout);
				Map<Object, Object> resMap = authenticatedService.getAuthenticatedResultByBatchInterface(authVo,productList);
				Result = (String) resMap.get("result");
				String batchauthresult = (String) resMap.get("batchauthresult");
				map.put("batchauthresult", batchauthresult);
				if(!"0".equals(Result)) {// 用户未订购，查看本地免
					for(int i = 0; i < productList.size(); i++) {
						productVo = productList.get(i);
						if(productVo.getF_sp_type()==3) {
							wfResult = payServiceBean.getWeekFreeResult(userID,productVo.getF_sp_id());
							break;
						}
					}
				}
			}else {
				for(int i = 0; i < productList.size(); i++) {
					productVo = productList.get(i);
					if(productVo.getF_sp_type()==10) { //10代表为服务ID
						Result= authenticatedService.getAuthenticatedResult(userID,productVo.getF_sp_productcode(),readTimeOut,connectTimeout);
						//break; //如果为服务ID，则只需要鉴权一次就要break，前期因教育K歌业务很多产品包没有服务id，所以要循环统一
					}else if(productVo.getF_sp_type()==3) { //本地免
						wfResult = payServiceBean.getWeekFreeResult(userID,productVo.getF_sp_id());
					}else{ //其他为产品ID
						AuthenticatedVo authVo = new AuthenticatedVo();
						authVo.setServerid(userID);
						authVo.setProductCode(productVo.getF_sp_productcode());
						authVo.setReadTimeOut(readTimeOut);
						authVo.setConnectTimeout(connectTimeout);
						Result= authenticatedService.getAuthenticatedResultByProductID(authVo);
					}
					if(Result=="0"||"0".equals(Result)) {
						break;
					}
				}
			}
			int flag = 0; //判断是否取到包月产品ID，如果未取到需要取第1个产品id，0为服务id
			for(int i = 0; i < productList.size(); i++) { //为了获取可被定购的产品id，默认给包月产品id，当没有包月产品id时，应提取第一个产品id，程序不判断是单点还是其他包季包年等。
				productVo = productList.get(i);
				if(productVo.getF_sp_type()==1) { //1代表包月
					map.put("productCode", productVo.getF_sp_productcode());
					map.put("productType", productVo.getF_sp_type()+"");
					map.put("productId", productVo.getF_sp_id()+"");
					flag = 1;
					break;
				}
			}
			if(flag==0 && productList.size()>=2) { //判断是否取到包月产品ID，如果未取到需要取第1个产品id，0为服务id
				productVo = productList.get(1);
				map.put("productCode", productVo.getF_sp_productcode());
				map.put("productType", productVo.getF_sp_type()+"");
				map.put("productId", productVo.getF_sp_id()+"");
			}
			if(map.get("productId")!=null){
				List<PmsOrgVo> orgList=commonsServiceBean.selectOrgCodeByProductId(Integer.parseInt(map.get("productId")));
				String SPID="";
				if(orgList!=null && orgList.size() > 0){
					SPID=orgList.get(0).getF_po_code();
				}
				if(SPID ==""||"".equals(SPID)){
					SPID="120000";
				}
				map.put("SPID", SPID);
			}
			map.put("Result", Result);
		}
		map.put("wfResult", wfResult);
		return map;
	}

	/**
	 * 行业产品包鉴权
	 * @param userID				用户账号
	 * @param strategyID			策略id
	 * @param serviceType			业务类型
	 * @param request
	 * @param response
	 * @return map{
	 * 				Result:鉴权结果
	 * 				authFlag:描述
	 * 				productCode:产品code 对应表sys_product——f_sp_productcode字段
	 * 				productType:产品类型 对应表sys_product——f_sp_type字段
	 * 				productId:产品id 对应表sys_product——f_sp_id字段
	 * 				SPID:企业spid 对应表pms_org——f_po_code字段
	 * 				}
	 */
	@RequestMapping("/service/authenticationByIndustryUserID")
	@ResponseBody
	public Object getAuthenticatedResultByIndustryUserID(String userID,int strategyID,String serviceType,String contentID,HttpServletRequest request,HttpServletResponse response) {
		Map<String, String> map=new HashMap<String, String>();
		if(strategyID == 1){
			String areaId = commonsServiceBean.selectAreaIdByServerId(userID);
			if(areaId=="0571"||areaId.equals("0571")) {
				areaId = "571";
			}
			SysProductVo productVo = commonsServiceBean.selectProductByAreaId(areaId,serviceType);
			map = commonsServiceBean.getAuthResultMap(productVo,userID,contentID,request,response);
		}else if(strategyID == 2){
			SysProductVo productVo = commonsServiceBean.selectProductByAreaId("330000",serviceType);
			map = commonsServiceBean.getAuthResultMap(productVo,userID,serviceType,request,response);
		}
		return map;
	}


	/**
	 *已订购产品包查询---有新产品时需接口方配置新产品才能查到
	 */
	@RequestMapping("service/authenticationByunionProductId")
	@ResponseBody
	public Object getAuthenticationByunionProductId(String userId,HttpServletRequest request,HttpServletResponse response){
		Map<String,String> map = new HashMap<String, String>();
		AuthenticatedService authenticatedService = new AuthenticatedService(request,response);
		String result ="";
		result = authenticatedService.getProductsOrdered(userId);
		map.put("Result", result);
		LOG.debug("PayAction -->authenticationByunionProductId Result="+result);
		return map;

	}
	/**
	 *根据提供的渠道号查询用户相对应的已订购产品详情
	 * @param serverid	用户账号
	 * @param channelCode	渠道号  zengzhi 密匙：pmiTj2HZ
	 * @param Token 生成规则：token =  MD5(userid+channelCode+pwd) .  userid+channelCode+pwd后MD5(标准MD5 32位大写)
	 * @return map{
	 * 				result :结果标识	result=0 成功 result=-1 失败result=99 签名认证失败
	 *				msg : 具体查询结果详情
	 *				products : 具体查询内容结果详情
	 *				purchaseType : 0：包月支付  1：按次支付 2：按次或包月，保留，暂时不用
	 * }
	 */
	@RequestMapping("service/authenticationBychannelCode")
	@ResponseBody
	public Object authenticationGetProductsBychannelCode(AuthenticatedVo authVo,String server_channelCode,String server_channelCode_pwd,HttpServletRequest request,HttpServletResponse response){
		Map<String,String> map = new HashMap<String, String>();
		authVo.setReadTimeOut(3000);
		authVo.setConnectTimeout(3000);
		AuthenticatedService authenticatedService = new AuthenticatedService(request,response);
		String result ="";
		result = authenticatedService.getOrderedProductsBychannelCode(authVo,server_channelCode,server_channelCode_pwd);
		map.put("Result", result);
		LOG.debug("PayAction -->getOrderedProductsBychannelCode Result="+result);
		return map;
	}

	@RequestMapping("service/selectUserBill")
	@ResponseBody
	public Object selectUserBill(UserBillVo userBillVo){
		UserBillVo ubVo= payServiceBean.selectUserBill(userBillVo);
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("result", ubVo);
		return map;
	}

	@RequestMapping("service/insertUserBillDB")
	@ResponseBody
	public Object insertUserBillDB(UserBillVo userBillVo){
		int flag = payServiceBean.insertUserBillDB(userBillVo);
		return flag;
	}

	@RequestMapping("service/selectWxOrder")
	@ResponseBody
	public Object selectWxOrder(WchatOrderVo wchatOrderVo){
		WchatOrderVo vo= payServiceBean.selectWxOrder(wchatOrderVo);
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("result", vo);
		return map;
	}
}
